/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/util/PersistentSetSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: PersistentSetSerializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer.hbm;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;

import org.hibernate.Hibernate;
import org.hibernate.collection.internal.PersistentSet;

import com.elancom.framework.commons.json.serializer.JSONSerializer;
import com.elancom.framework.commons.json.serializer.ObjectSerializer;
import com.elancom.framework.commons.json.serializer.SerializeWriter;
import com.elancom.framework.commons.json.serializer.SerializerFeature;

/**
 * @author elancom
 * @date Apr 26, 2012
 */
public class PersistentSetSerializer implements ObjectSerializer {

	public static final PersistentSetSerializer INSTANCE = new PersistentSetSerializer();

	PersistentSetSerializer() { // package scope
	}

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
		final SerializeWriter out = serializer.getWriter();

		// lazy process
		final PersistentSet persistentSet = (PersistentSet) object;
		if (!Hibernate.isInitialized(persistentSet)) {
			if (serializer.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
				out.write("null");
			} else {
				out.write("[]");
			}
			out.write(",");

			if (out.isEnabled(SerializerFeature.PrettyFormat)) {
				serializer.println();
			}

			out.writeFieldName("$lazySet$" + fieldName);
			out.write("true");
			return;
		}

		try {
			final ObjectSerializer collectionSerializer = serializer.getObjectWriter(Collection.class);
			collectionSerializer.write(serializer, persistentSet, fieldName, fieldType);
		} finally {
		}
	}
}
